#include<iostream>
using namespace std;

struct ListNode {
     int val;
     ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
 };
 
class Solution {
public:
    ListNode* reverse(ListNode* head)
    {
        ListNode* newhead = new ListNode(0);
        ListNode* cur = head;
        while (cur)
        {
            ListNode* next = cur->next;
            cur->next = newhead->next;
            newhead->next = cur;
            cur = next;
        }
        cur = newhead->next;
        delete newhead;
        return cur;
    }

    ListNode* addTwoNumbers(ListNode* head1, ListNode* head2)
    {
        head1 = reverse(head1);
        head2 = reverse(head2);
        ListNode* cur1 = head1;
        ListNode* cur2 = head2;
        ListNode* rans = new ListNode(0);
        ListNode* cur = rans;
        int n = 0;
        int t = 0;
        while (cur1 || cur2 || t)
        {
            if (cur1)
            {
                t += cur1->val;
                cur1 = cur1->next;
            }
            if (cur2)
            {
                t += cur2->val;
                cur2 = cur2->next;
            }
            cur = cur->next = new ListNode(t % 10);
            t /= 10;
        }
        if (n == 1)
            cur->next = new ListNode(1);
        cur1 = rans->next;

        return reverse(cur1);
    }
};